<template>
    <div>
        <el-form :model="search" size="mini" inline label-width="80px">
            <el-form-item label="设备名称">
                <el-input v-model="search.name" style="width:180px" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="设备编号">
                <el-input v-model="search.device_no" style="width:180px" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="search.status" placeholder="请选择状态" style="width:180px">
                    <el-option label="在线" value="1"></el-option>
                    <el-option label="离线" value="6"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="安装位置">
                <el-input v-model="search.keyword" placeholder="请输入安装位置" style="width:180px"></el-input>
            </el-form-item>
            <el-form-item label="安装时间">
                <el-date-picker v-model="search.create_time" type="date" placeholder="请选择" style="width:180px"
                    value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getDeviceLists()" size="mini">搜索</el-button>
                <el-button type="warning" @click="reset" size="mini">重置</el-button>
                <el-button type="success" @click="onDownExcel" size="mini">导出</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" size="mini" border height="450px">
            <el-table-column label="序号" type="index" width="80"></el-table-column>
            <el-table-column label="设备类型" prop="mold_text"></el-table-column>
            <el-table-column label="设备名称" prop="name"></el-table-column>
            <el-table-column label="安装位置" prop="address"> </el-table-column>
            <el-table-column label="设备编号" prop="device_no"></el-table-column>
            <el-table-column label="设备状态" prop="status">
                <template #default="scope">
                    <div :style="scope.row.status === 1
            ? 'color:green;font-weight:bold'
            : scope.row.status == 2
                ? 'color:orange;font-weight:bold'
                : scope.row.status == 5
                    ? 'color:red;font-weight:bold'
                    : scope.row.status == 6
                        ? 'color:#ccc;font-weight:bold'
                        : scope.row.status == 3
                            ? 'color:orange;font-weight:bold'
                            : ''
            ">
                        {{ ['', '正常', '预警', '故障', '停用', '报警', '离线'][scope.row.status] }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="预警值" prop="warn_data">
                <template #default="scope">
                    <div v-for="(item, index) in scope.row.warn_data" :key="index">
                        {{ item.title + '：' + item.value }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="量值">
                <template #default="scope">
                    <span v-html="scope.row.measure" v-if="scope.row.measure"></span>
                </template>
            </el-table-column>
            <el-table-column label="安装时间">
                <template #default="scope">{{ $getDateTime(scope.row.create_time) }}</template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
                <template #default="scope">
                    <div>
                        <el-button type="info" @click="showDetail(scope.row)" size="mini">查看历史</el-button>
                    </div>
                    <div style="margin-top: 10px">
                        <!-- <el-button
                v-if="scope.row.name_id == 157 || scope.row.mold_id == 30"
                type="danger"
                size="mini"
                @click="playVideoEvent(scope.row)"
                >视频监控</el-button
              > -->
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination @current-change="handleCurrentChange" v-model:currentPage="tableDataInfo.page"
                :page-count="tableDataInfo.total_page" :total="tableDataInfo.total" background
                layout="total,prev, pager, next, jumper">
            </el-pagination>
        </div>
        <!-- 详情 start -->
        <el-dialog v-model="showDetailsDialog" v-if="showDetailsDialog" width="70%" @close="closeDetailsDialog"
            :close-on-click-modal="false">
            <el-tabs v-model="activeName" type="card" class="demo-tabs" @click="handleClick">
                <el-tab-pane label="详情" name="detail"></el-tab-pane>
                <el-tab-pane label="设备上报记录" name="report"></el-tab-pane>
            </el-tabs>
            <div v-if="activeName === 'detail'">
                <deviceReportShow :details="details" :isAll="true"></deviceReportShow>
            </div>
            <div v-else class="report-wrapper">
                <el-table :data="historyTabletableData" border style="width: 100%">
                    <el-table-column prop="device_no" label="设备编号"> </el-table-column>
                    <el-table-column label="事件">
                        <template #default="scope">
                            <div v-html="scope.row.event_type"></div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="create_time" label="开始时间">
                        <template #default="scope">{{ $getDateTime(scope.row.create_time) }}</template>
                    </el-table-column>

                </el-table>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDetailsDialog">返 回</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 详情 end -->
        <!-- 详情 start -->
        <el-dialog v-model="innerShowDetailsDialog" v-if="innerShowDetailsDialog" width="70%"
            @close="closeInnerDetailsDialog" :close-on-click-modal="false">
            <deviceReportShow :details="innerdetails" :isAll="true"></deviceReportShow>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="innerShowDetailsDialog = false">返 回</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 详情 end -->
        <el-dialog v-model="playVideoBoxDialog" width="50%" destroy-on-close class="detailsDialog">
            <div style="width: 100%; height: 50vh">
                <iframe id="dplayer" :src="playingVideoUrl" style="width: 100%; height: 100%"></iframe>
            </div>
        </el-dialog>
    </div>
</template>

<script>
//引入 hls与dplayer 用于解析播放视频
import Hls from 'hls.js'
import Dplayer from 'dplayer'
import { useRouter } from 'vue-router'
import { setDeviceData } from '@/util/deviceData'
// import Echarts from '@/util/echarts'
import { markRaw } from 'vue'

import { ref, onMounted } from 'vue'
// 标识组件
import deviceReportShow from './DeviceReportShow.vue'

// import {ref} from 'vue'
export default {
    props: ['rows', 'deviceStatus', 'deviceMold', 'status'],
    components: {
        deviceReportShow
    },
    data() {
        return {
            shows: false,
            activeName: 'detail',
            reportList: [],
            tableData: [],
            tableDataInfo: '',
            moldType: [],
            updata_times: '',
            search: {},
            searchForm: {
                method: 1,
                status: 1
            },
            //   status: [
            //     // 1. 正常，2.预警，3.故障,4.停用，5报警，6-不在线 7-在线
            //     { label: '正常', value: 1 },
            //     { label: '预警', value: 2 },
            //     { label: '故障', value: 3 },
            //     { label: '停用', value: 4 },
            //     { label: '报警', value: 5 },
            //     { label: '离线', value: 6 },
            //     { label: '在线', value: 7 }
            //   ],
            defaultProps: {
                children: 'sub_item',
                label: 'name',
                value: 'id',
                checkStrictly: true
            },
            historyInfoDialog: false,
            historyTabletableData: [],
            historyTableDataInfo: '',
            device_no: '',
            device_method: '',
            showDetailsDialog: false,
            innerShowDetailsDialog: false,
            details: {},
            playingVideoUrl: '',
            playVideoBoxDialog: false,
            trenChart: '',
            aqwe: ''
        }
    },
    mounted() {
        this.getDeviceLists()
        // this.rendertrenChart()
    },
    created() {
        this.getMoldType()
    },
    methods: {
        rendertrenChart() {
            this.trenChart = markRaw(Echarts.init(this.$refs.trenChart))
            let data = this.historyTabletableData
            let dateData = []
            let seriesDataArr = []
            let seriesDataArrName = []
            let seriesData = []
            let series = []
            data.map((item) => {
                seriesDataArr = item.measure.split('<br />')
                seriesDataArr.map((item2) => {
                    if (item2.length) {
                        if (seriesDataArrName.indexOf(item2.split(':')[0]) == -1) {
                            seriesDataArrName.push(item2.split(':')[0])
                            series.push({
                                name: item2.split(':')[0],
                                type: 'line',
                                stack: 'Total',
                                data: []
                            })
                        }
                        seriesData.push({
                            name: item2.split(':')[0],
                            data: item2.split(':')[1],
                            company: item2.split(':')[1].replace(/[^a-zA-Z]/g, '')
                        })
                    }
                })
                dateData.push(this.$getDateTime(item.update_time))
            })
            series.map((item) => {
                seriesData.map((item2) => {
                    if (item.name == item2.name) {
                        item.data.push({
                            value: parseFloat(item2.data),
                            company: item2.company
                        })
                    }
                })
            })

            let option = {
                // title: {
                //   text: 'Stacked Line'
                // },
                tooltip: {
                    trigger: 'axis',
                    formatter(params) {
                        let str = params[0]['axisValue']
                        params.forEach((item) => {
                            str += '</br>' + item.marker + item.seriesName + '&nbsp;：' + item.data.value + item.data.company
                        })
                        return str
                    }
                },
                legend: {
                    data: seriesDataArrName
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    // feature: {
                    //   saveAsImage: {}
                    // }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: dateData
                },
                yAxis: {
                    type: 'value'
                },
                series: series
            }
            this.trenChart.setOption(option)
        },

        playVideoEvent(row) {
            this.$api.post('/unit/DeviceInstall/showDevice', { device_no: row.device_no }).then((res) => {

                let { video_url } = res.data
                if (!video_url) {
                    this.$message.error('视频连接错误，请稍后再试')
                    return false
                }
                console.log(res.data)
                this.playingVideoUrl = video_url
                if (res.data.factory_name == '萤石云' || res.data.factory_name == '智城') {
                    this.playVideoBoxDialog = true
                } else if (res.data.installer == '赋安云' || res.data.factory_name == '海康') {
                    this.$router.push({
                        name: 'video',
                        query: {
                            data: video_url
                        }
                    })
                }
            })
        },
        handleClick() {
            if (this.activeName === 'report') {
                this.getHistoryInfoList()
            }
            if (this.activeName === 'report') {
            }
        },
        closeDetailsDialog() {
            this.activeName = 'detail'
            this.showDetailsDialog = false
        },
        innerShowDetail(row) {
            this.innerdetails = row
            this.innerShowDetailsDialog = true
            this.ondetailShow(row)
        },
        showDetail(row) {
            this.details = row
            this.showDetailsDialog = true
            this.ondetailShow(row)
        },
        reset() {
            this.search = {}
            this.getDeviceLists(1)
        },
        onDownExcel() {
            this.$api
                .post(
                    '/unit/DeviceWarning/newDeviceListExcl',
                    {
                        status: this.status,
                        ...this.search
                    },
                    {
                        responseType: 'blob'
                    }
                )
                .then((res) => {
                    const blob = new Blob([res], {
                        type: 'application/vnd.ms-excel'
                    })

                    if (window.navigator.msSaveOrOpenBlob) {
                        //兼容IE10
                        navigator.msSaveBlob(blob, '导出文件.xlsx')
                    } else {
                        const href = URL.createObjectURL(blob) //创建新的URL表示指定的blob对象
                        const a = document.createElement('a') //创建a标签
                        a.style.display = 'none'
                        a.href = href // 指定下载链接
                        a.download = '导出文件.xlsx' //指定下载文件名
                        a.click() //触发下载
                        URL.revokeObjectURL(a.href) //释放URL对象
                    }
                })
        },
        ondetailShow(row) {
            this.device_no = row.device_no
            let new_device_data = row.device_method
            if (new_device_data == '4gWirelessPressure') {
                new_device_data = 'fgWirelessPressure'
            }
            if (new_device_data == '4gWirelessLiquidLevel') {
                new_device_data = 'fgWirelessLiquidLevel'
            }
            this.device_method = new_device_data
        },
        formatterTime(row, column, cellValue, index) {
            return this.$getDateTime(cellValue)
        },
        showHistoryInfo(row) {
            this.historyInfoDialog = true
            this.device_no = row.device_no
            this.getHistoryInfoList()
        },
        async getHistoryInfoList(page) {
            let pageNum = 1
            if (page) {
                pageNum = page
            }
            let resp = await this.$api.post('/unit/DeviceWarning/Lists', {
                page: pageNum,
                rows: 6,
                device_no: this.device_no,
                device_method: 1
            })
            this.historyTabletableData = await setDeviceData(resp.data.list)
            // this.rendertrenChart()
            delete resp.data.list
            this.historyTableDataInfo = resp.data
            let chartRes = await this.$api.post('/unit/DeviceLog/Trend', {
                time_begin: '',
                time_end: '',
                device_no: this.device_no
            })
        },
        //   搜索
        searchBtn() {
            this.getDeviceLists()
        },
        // 重置
        refreshBtn() {
            this.searchForm = {
                mold_id: '',
                status: '',
                start_update_time: '',
                end_update_time: ''
            }
            this.getDeviceLists()
        },
        getDateTime(row, column, cellValue, index) {
            console.log(row, column, cellValue, index, cellValue)
            return this.$getDateTime(cellValue)
        },
        deviceStatus(row, column, cellValue, index) {
            let temp = ['', '正常', '预警', '故障', '停用', '报警', '离线']
            return temp[cellValue]
        },
        handleCurrentChange(e) {
            this.getDeviceLists(e)
        },
        async getDeviceLists(page) {
            let pageNum = 1
            if (page) {
                pageNum = page
            }
            let searchParams = JSON.parse(JSON.stringify(this.searchForm))
            if (this.updata_times) {
                searchParams.start_update_time = this.updata_times[0] / 1000
                searchParams.end_update_time = this.updata_times[1] / 1000 + 86400
            }
            let params = {
                // page: pageNum,
                // rows: this.rows ? this.rows : 13,
                // ...searchParams
                status: this.status,
                ...this.search
            }
            let resp = await this.$api.post('/unit/DeviceWarning/newDeviceList', params)
            this.tableData = await setDeviceData(resp.data)

            //   this.tableDataInfo = resp.data
        },
        // 设备类型
        getMoldType() {
            this.$api.get('/unit/DeviceBase/moldTree').then((res) => {
                this.moldType = res.data
            })
        }
    }
}
</script>

<style scoped lang="scss">
.block {
    display: block;
    // justify-content: center;
    // align-items: center;
    margin-top: 20px;
}

.el-col {
    display: flex;
    white-space: nowrap;
    align-items: center;
}

:deep(.el-range-separator) {
    width: 30px;
}

:deep(.el-scrollbar__wrap) {
    // overflow: hidden;
}

.report-wrapper {
    max-height: 530px;
    overflow-x: hidden;
    overflow-y: auto;

    .device-report-list {
        height: auto !important;
        max-height: 50vh;
        margin-bottom: 20px;
    }
}
</style>
